package vip.wangwenhao.sso.utils;

import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import vip.wangwenhao.common.constants.CommonConstants;

/**
 * @author wwh
 * @date 2020年01月17日 10:31
 */
@Slf4j
public class Oauth2EncryptUtils {
    /**
     * md5 加盐加散列
     *
     * @param password        明文密码
     * @param salt            盐
     * @param iteration       散列次数
     * @param passwordEncoder 加密算法
     * @return
     */
    public static String encode(String password, String salt, Integer iteration, PasswordEncoder passwordEncoder) {
        try {
            Preconditions.checkState(StringUtils.isNotBlank(password), "password is null");
            Preconditions.checkState(StringUtils.isNotBlank(salt), "salt is null");
            Preconditions.checkNotNull(iteration, "iteration is null");
            Preconditions.checkState(iteration >= CommonConstants.TWO && iteration < CommonConstants.FIVE, "iteration is invalid");
            for (int i = CommonConstants.ZERO; i < iteration; i++) {
                if (CommonConstants.ONE.equals(i)) {
                    StringBuffer stringBuffer = new StringBuffer(password);
                    stringBuffer.insert(CommonConstants.TWO, salt);
                    stringBuffer.insert(CommonConstants.FIVE, salt);
                    stringBuffer.insert(CommonConstants.ELEVEN, salt);
                    password = stringBuffer.toString();
                }
                password = passwordEncoder.encode(password);
            }
            return password;
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

}